package com.wywah.yunduo.security.service.impl;

import com.wywah.yunduo.orm.bean.UserInfo;
import com.wywah.yunduo.orm.dao.UserInfoMapper;
import com.wywah.yunduo.security.core.LoginUserInfo;
import com.wywah.yunduo.security.core.YunduoAuthorizationGrantType;
import com.wywah.yunduo.security.service.YunDuoUser;
import com.wywah.yunduo.security.service.YunduoCustomUserDetailsService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.List;
import java.util.Objects;

/**
 * 内部员工
 */
@Configuration
public class EmployeeUserDetailServiceImpl implements YunduoCustomUserDetailsService {

    private final UserInfoMapper userInfoMapper;
    @Override
    public boolean support(String clientId, String grantType) {
        return YunduoAuthorizationGrantType.EMPLOYEE.getValue().equals(grantType);
    }

    public EmployeeUserDetailServiceImpl(UserInfoMapper userInfoMapper) {
        this.userInfoMapper = userInfoMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<UserInfo> list = userInfoMapper.findUserByYhid(username);
        if(Objects.nonNull(list) && !list.isEmpty()) {
            LoginUserInfo userInfo = new LoginUserInfo();
            userInfo.setUser(list.get(0));
            return userInfo;
        }
        return null;
    }
}
